package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.BeanUtils;
import com.scs.application.modules.base.entity.ReagentTeamUser;
import com.scs.application.modules.base.mapper.ReagentTeamUserMapper;
import com.scs.application.modules.base.mapper.StaffMapper;
import com.scs.application.modules.base.service.ReagentTeamUserService;
import com.scs.application.modules.base.service.StaffService;
import com.scs.application.modules.sys.entity.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 试剂组人员 服务实现类
 * </p>
 */
@Service
public class ReagentTeamUserServiceImpl extends BaseServiceImpl<ReagentTeamUserMapper, ReagentTeamUser> implements ReagentTeamUserService {

    @Resource
    private StaffService staffService;

    @Resource
    private StaffMapper staffMapper;

    @Override
    public Map<String, Integer> saveUser(List<User> users, String reagentTeamId) {
        Map<String, Integer> result = new HashMap<>();
        int updateCount = 0;
        int addCount = 0;
        List<String> codeList = users.stream().map(User::getCode).collect(Collectors.toList());
        List<ReagentTeamUser> teamUserList = this.list(new QueryWrapper<ReagentTeamUser>().eq("reagent_team_id", reagentTeamId).in("code", codeList));

        List<ReagentTeamUser> saveOrUpdateList = new ArrayList<>();
        for (User staff : users) {
            boolean find = false;
            for (ReagentTeamUser teamUser : teamUserList) {
                if (staff.getCode().equalsIgnoreCase(teamUser.getCode())) {
                    // 已存在待更新的user
                    BeanUtils.copyProperties(staff, teamUser, "id", "creator", "gmtCreate");
                    teamUser.setUserId(staff.getId());
                    saveOrUpdateList.add(teamUser);
                    updateCount++;
                    find = true;
                    break;
                }
            }
            if (!find) {
                // 新增加的user
                ReagentTeamUser teamUser = new ReagentTeamUser();
                BeanUtils.copyProperties(staff, teamUser, "id", "creator", "gmtCreate");
                teamUser.setUserId(staff.getId());
                teamUser.setReagentTeamId(reagentTeamId);
                saveOrUpdateList.add(teamUser);
                addCount++;
            }
        }
        if (saveOrUpdateList.size() > 0) {
            this.saveOrUpdateBatch(saveOrUpdateList);
        }
        result.put("updateCount", updateCount);
        result.put("addCount", addCount);
        return result;
    }
}
